import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { User } from '@/types';
import { Platform } from 'react-native';

interface AuthState {
  user: User | null;
  isAuthenticated: boolean;
  isLoading: boolean;
  error: string | null;
  login: (email: string, password: string) => Promise<void>;
  logout: () => void;
  signup: (name: string, email: string, password: string) => Promise<void>;
}

// Mock user data for demo purposes
const mockUser: User = {
  id: '1',
  name: 'Alex Chen',
  email: 'alex@example.com',
  avatar: 'https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&auto=format&fit=crop&w=256&q=80',
  streak: 5,
  totalStudyTime: 320,
};

// Create a fallback storage for web environments where AsyncStorage might not be available
const createNoopStorage = () => {
  return {
    getItem: (_name: string) => Promise.resolve(null),
    setItem: (_name: string, _value: string) => Promise.resolve(),
    removeItem: (_name: string) => Promise.resolve(),
  };
};

// Use AsyncStorage when available, otherwise use a noop storage
const storage = Platform.OS === 'web' 
  ? createNoopStorage()
  : AsyncStorage;

export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      user: null,
      isAuthenticated: false,
      isLoading: false,
      error: null,
      
      login: async (email: string, password: string) => {
        set({ isLoading: true, error: null });
        
        try {
          // Simulate API call
          await new Promise(resolve => setTimeout(resolve, 1000));
          
          // For demo, accept any non-empty credentials
          if (!email || !password) {
            throw new Error('Please enter both email and password');
          }
          
          set({ 
            user: mockUser,
            isAuthenticated: true,
            isLoading: false 
          });
        } catch (error) {
          set({ 
            error: error instanceof Error ? error.message : 'Login failed',
            isLoading: false 
          });
        }
      },
      
      logout: () => {
        set({ user: null, isAuthenticated: false });
      },
      
      signup: async (name: string, email: string, password: string) => {
        set({ isLoading: true, error: null });
        
        try {
          // Simulate API call
          await new Promise(resolve => setTimeout(resolve, 1000));
          
          if (!name || !email || !password) {
            throw new Error('Please fill in all fields');
          }
          
          // Create a new user based on the mock user
          const newUser: User = {
            ...mockUser,
            id: Math.random().toString(36).substring(2, 9),
            name,
            email,
            streak: 0,
            totalStudyTime: 0,
          };
          
          set({ 
            user: newUser,
            isAuthenticated: true,
            isLoading: false 
          });
        } catch (error) {
          set({ 
            error: error instanceof Error ? error.message : 'Signup failed',
            isLoading: false 
          });
        }
      }
    }),
    {
      name: 'auth-storage',
      storage: createJSONStorage(() => storage),
    }
  )
);